<!--
 * @Author: xiaxia
 * @Description: 
 * @Date: 2024-05-22 09:55:13
 * @LastEditTime: 2024-05-24 18:00:25
 * @FilePath: \vue-admin-template\src\components\tool\Prints.vue
-->
<template>
  <div>
    <canvas id="pdfCanvas" class="cav"></canvas>
    <el-dialog
      title="确认打印"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <div class="row">
        <span>
          二次确认
        </span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="confirmPrint()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {lodopImageBase64 , getObjectURL, getFileBase64} from '@/utils/printjs.js'
  import {getLodop} from '@/utils/LodopFuncs'
  import * as pdfjsLib from "pdfjs-dist/es5/build/pdf"
  const pdfjsWorker = import("pdfjs-dist/es5/build/pdf.worker.entry")
  pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker
  export default {
    name: 'Prints',
    props: {
      printer: { type: String, default: null }, //打印机
      path: { type: String, default: null }, // 打印设置-接口配置
      topMargin: { type: String, default: '' }, // 上边距
      leftMargin: { type: String, default: '' }, // 左边距
      dyNumber:{type:Number,default: 1}, // 打印份数
      paperDir:{type:String,default: '1'}, // 纸张方向
      paperSize:{type:String,default:'1'}, // 纸张大小
    },
    data() {
      return {
        dialogVisible: false,
        preview: false, // 打印预览
      }
    },
    methods: {
      // 二次确认前
      hprints(val) {
        if(val==0){
          this.preview = true
          this.confirmPrint()
          console.log('打印预览', val)
        } else {
          this.preview = false
          this.dialogVisible = true
          console.log('直接打印');
        }
      },
      // 确认按钮
      async confirmPrint() {
        this.dialogVisible = false
        switch (this.path) {
          case '1': // pdf打印
            await this.pdfPrint()
            console.log('pdf打印完成')
            break
          case '2': // img打印
            await this.imgPrint()
            this.stopPrint('img打印完成')
            break
        }
      },
      // pdf打印 '1'
      async pdfPrint() {
        let answer = null
        let LODOP = getLodop()
        // 1. pdf地址
        const url = "http://localhost:8000/CLodopDemos/PDFDemo.pdf";
        // const url = "http://localhost:8000/CLodopDemos/0test(long).pdf";
        const zhUrl = await getFileBase64(url)
        const loadingTask = pdfjsLib.getDocument(zhUrl)
        // 2. 文件流
        // let strURL = file.address // pdf地址
        // let res = await getPrintFeil({FileAddress: strURL}) // 请求后端
        // let bolbFile = new Blob([res.data], { type: 'application/pdf; charset=utf-8' })
        // let blobUrl =  getObjectURL(bolbFile)
        // const loadingTask = pdfjsLib.getDocument(blobUrl)

        let pdf = null
        try {
          pdf = await loadingTask.promise
        } catch(e) {
          this.progresshow = false // 进度条
          console.log(e, '错误--------------');
          return answer = { success: false,msg: "未查询到pdf地址,请联系管理员" }
        }

        let numPages = pdf.numPages
        // 1. 如果当前打印的页数 <= 10
        if(numPages <= 10) {
          LODOP.PRINT_INIT('pdf打印<=10')

          if (this.paperSize == '2') { // 'A5'
            console.log('A5A5A5A5A5A5A5A5A5A5A5A5A5A5A5A5')
            if(this.paperDir == 2) { // '2' 纸张方向横向
              LODOP.SET_PRINT_PAGESIZE(2, 1480, 2100, "A5") // 设置纸张大小A5纵向打印
              console.log('横向')
            } else {// '1' 纸张方向纵向
              LODOP.SET_PRINT_PAGESIZE(1, 1480, 2100, "A5") // 设置纸张大小A5纵向打印
              console.log('纵向')
            }
          } else { // 'A4
            console.log('A4A4A4A4A4A4A4A4A4A4A4A4A4A4A4A4')
            if(this.paperDir == 2) { // 2 纸张方向横向
              console.log('横向')
              LODOP.SET_PRINT_PAGESIZE(2, 2100, 2970, "A4"); // 设置纸张大小A4纵向打印
            } else {// 1 纸张方向纵向
              console.log('纵向')
              LODOP.SET_PRINT_PAGESIZE(1, 2100, 2970, "A4"); // 设置纸张大小A4纵向打印
            }
          }

          for(let i=1; i<=numPages; i++){
            await this.CreateOnePage(pdf, i)
            this.percentage = Math.floor((i/numPages)*100)
          }
          LODOP.SET_PRINT_COPIES(this.dyNumber)
          console.log(this.printer, 'this.printer');
          if (this.preview) {
            LODOP.PREVIEW()
          } else {
            LODOP.SET_PRINTER_INDEX(this.printer)
            LODOP.PRINT()
          }

          this.$message.success('发票 '+' 解析完成正在发送请求到打印机,请耐心等待......');
          return new Promise((resolve) => {
            LODOP.On_Return = function (TaskID, Value) {
              if(Value){
                this.percentage = 100
                console.log('打印成功：发送打印请求成功');
                answer = { success: true, msg: "发送打印请求成功" }
              } else {
                this.percentage = 0
                console.log('发送打印请求失败');
                answer = { success: false, msg: "发送打印请求失败" }
              }
              resolve(answer); // 完成Promise
            }
          })
        }
        // 2. 当前页数>10--需要进行分组 
        else {
          let num1 = Math.ceil(numPages/10) // 向上取整
          for (let it = 0; it <= num1-1; it++) {
            LODOP.PRINT_INIT('pdf打印>10')
            if(this.paperSize == '2') { // 'A5'
              if(this.paperDir == 2) {
                console.log('横向')
                LODOP.SET_PRINT_PAGESIZE(2, 1480, 2100, "A5"); // 设置纸张大小A5横向打印
              } else {
                console.log('纵向')
                LODOP.SET_PRINT_PAGESIZE(1, 1480, 2100, "A5"); // 设置纸张大小A5纵向打印
              }
            } else { // 'A4'
              if(this.paperDir == 2) {
                console.log('横向')
                LODOP.SET_PRINT_PAGESIZE(2, 2100, 2970, "A4"); // 设置纸张大小A4横向打印
              } else {
                console.log('纵向')
                LODOP.SET_PRINT_PAGESIZE(1, 2100, 2970, "A4"); // 设置纸张大小A4纵向打印
              }
            }
            if(it == 0) {
              for (let ind = 1; ind <= 10; ind++) {
                await this.CreateOnePage(pdf, ind)
                this.percentage = Math.floor((ind/numPages)*100)
              }
            } else{
              for (let ind = 1; ind <= 10; ind++) {
                if(ind == 10){
                  await this.CreateOnePage(pdf, parseInt(it+1+''+0))
                  this.percentage = Math.floor((parseInt(it+1+''+0)/numPages)*100)
                  if(parseInt(it+1+''+0)==numPages) break;
                } else {
                  await this.CreateOnePage(pdf, parseInt(it+''+ind))
                  this.percentage = Math.floor((parseInt(it+''+ind)/numPages)*100)
                  if(parseInt(it+''+ind)==numPages) break;
                }
              }
            }
            LODOP.SET_PRINT_MODE("CUSTOM_TASK_NAME",'pdf打印'+'第'+(it+1)+'份') // 单独任务名
            LODOP.SET_PRINT_COPIES(this.dyNumber) // 打印份数
            if (this.preview) {
              LODOP.PREVIEW()
            } else {
              LODOP.SET_PRINTER_INDEX(this.printer)
              LODOP.PRINT()
            }

            this.$message.success('发票 ' +' 解析完成正在发送请求到打印机,请耐心等待......');
            return new Promise((resolve) => {
              LODOP.On_Return = function (TaskID, Value) {
                if(Value){
                  this.percentage = 100
                  console.log('打印成功：发送打印请求成功');
                  answer = { success: true, msg: "发送打印请求成功" }
                } else {
                  this.percentage = 0
                  console.log('发送打印请求失败');
                  answer = { success: false, msg: "发送打印请求失败" }
                }
                resolve(answer); // 完成Promise
              }
            })
          }
        }
      },
      // pdf解析
      async CreateOnePage(pdf, i){
        LODOP.NewPage();
        let pdfId = "pdf" + i;
        const newCanvas = document.createElement("canvas");
        newCanvas.setAttribute("id", pdfId);
        const page = await pdf.getPage(i);
        const context = newCanvas.getContext("2d");
        const viewport = page.getViewport({ scale: 7});
        newCanvas.height = viewport.height;
        newCanvas.width = viewport.width;
        const renderContext = {
          canvasContext: context,
          viewport: viewport,
        }
        await page.render(renderContext).promise;
        const img = newCanvas.toDataURL("image/jpeg");
        console.log("Page rendered", img);

        LODOP.ADD_PRINT_IMAGE(this.topMargin, this.leftMargin, "95%", "95%", img)
        LODOP.SET_PRINT_STYLEA(0,"Stretch",2);
        newCanvas.remove();
      },
      // img打印 '2
      imgPrint() {},
    }
  }
</script>

<style>

</style>